﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.model.Instance;
using l1cs.server.datatables;
using MySql.Data.MySqlClient;
using System.Data;
using l1cs.server.templates;
using l1cs.server.utils;

namespace l1cs.server.model
{
    public class L1DwarfInventory : L1Inventory
    {
        public L1DwarfInventory( L1PcInstance owner )
        {
            _owner = owner;
        }

        // ＤＢのcharacter_itemsの読込
        override public void loadItems() {
            string sqlstr = "SELECT * FROM character_warehouse WHERE account_name = ?1";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand(sqlstr);
                cmd.Parameters.Add("?1", MySqlDbType.String).Value = _owner.getAccountName();
                foreach (DataRow dr in wrapper.GetDataTable(cmd).Rows)
                {
                    L1ItemInstance item = new L1ItemInstance();
                    int objectId = SqlUtils.toInt(dr["id"]);
                    item.setId(objectId);
                    L1Item itemTemplate = ItemTable.getInstance().getTemplate(SqlUtils.toInt(dr["item_id"]));
                    item.setItem(itemTemplate);
                    item.setCount(SqlUtils.toInt(dr["count"]));
                    item.setEquipped(false);
                    item.setEnchantLevel(SqlUtils.toInt(dr["enchantlvl"]));
                    item.setIdentified(SqlUtils.toInt(dr["is_id"]) != 0 ? true : false);
                    item.set_durability(SqlUtils.toInt(dr["durability"]));
                    item.setChargeCount(SqlUtils.toInt(dr["charge_count"]));
                    item.setRemainingTime(SqlUtils.toInt(dr["remaining_time"]));
                    item.setLastUsed(SqlUtils.toDateTime(dr["last_used"]));
                    item.setBless(SqlUtils.toInt(dr["bless"]));
                    item.setAttrEnchantKind(SqlUtils.toInt(dr["attr_enchant_kind"]));
                    item.setAttrEnchantLevel(SqlUtils.toInt(dr["attr_enchant_level"]));

                    _items.Add(item);
                    L1World.getInstance().storeObject(item);
                }
            }
        }

        // ＤＢのcharacter_warehouseへ登録
        override public void insertItem( L1ItemInstance item )
        {
            String sqlstr = @"INSERT INTO character_warehouse SET 
                                id                 = ?1,
                                account_name       = ?2,
                                item_id            = ?3,
                                item_name          = ?4,
                                count              = ?5,
                                is_equipped        = 0,
                                enchantlvl         = ?6,
                                is_id              = ?7,
                                durability         = ?8,
                                charge_count       = ?9,
                                remaining_time     = ?10,
                                last_used          = ?11,
                                bless              = ?12,
                                attr_enchant_kind  = ?13,
                                attr_enchant_level = ?14";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = item.getId();
                cmd.Parameters.Add( "?2", MySqlDbType.String ).Value = _owner.getAccountName();
                cmd.Parameters.Add( "?3", MySqlDbType.Int32 ).Value = item.getItemId();
                cmd.Parameters.Add( "?4", MySqlDbType.String ).Value = item.getName();
                cmd.Parameters.Add( "?5", MySqlDbType.Int32 ).Value = item.getCount();
                cmd.Parameters.Add( "?6", MySqlDbType.Int32 ).Value = item.getEnchantLevel();
                cmd.Parameters.Add( "?7", MySqlDbType.Int32 ).Value = item.isIdentified() ? 1 : 0;
                cmd.Parameters.Add( "?8", MySqlDbType.Int32 ).Value = item.get_durability();
                cmd.Parameters.Add( "?9", MySqlDbType.Int32 ).Value = item.getChargeCount();
                cmd.Parameters.Add( "?10", MySqlDbType.Int32 ).Value = item.getRemainingTime();
                cmd.Parameters.Add( "?11", MySqlDbType.DateTime ).Value = item.getLastUsed();
                cmd.Parameters.Add( "?12", MySqlDbType.Int32 ).Value = item.getBless();
                cmd.Parameters.Add( "?13", MySqlDbType.Int32 ).Value = item.getAttrEnchantKind();
                cmd.Parameters.Add( "?14", MySqlDbType.Int32 ).Value = item.getAttrEnchantLevel();
                wrapper.ExecNonQuery( cmd );
            }
        }

        // ＤＢのcharacter_warehouseを更新
        override public void updateItem( L1ItemInstance item )
        {
            String sqlstr = "UPDATE character_warehouse SET count = ? WHERE id = ?1";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = item.getCount();
                cmd.Parameters.Add( "?2", MySqlDbType.Int32 ).Value = item.getId();
                wrapper.ExecNonQuery( cmd );
            }
        }

        // ＤＢのcharacter_warehouseから削除
        override public void deleteItem( L1ItemInstance item )
        {
            string sqlstr = "DELETE FROM character_warehouse WHERE id = ?1";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = item.getId();
                wrapper.ExecNonQuery( cmd );
            }

            _items.Remove( item );
        }

        public static void present( String account, int itemid, int enchant, int count )
        {

            L1Item temp = ItemTable.getInstance().getTemplate( itemid );
            if ( temp == null )
            {
                return;
            }

            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                string sqlstr;
                MySqlCommand cmd;
                if ( account.Equals( "*" ) )
                {
                    sqlstr = "SELECT * FROM accounts";
                    cmd = new MySqlCommand( sqlstr );
                }
                else
                {
                    sqlstr = "SELECT * FROM accounts WHERE login=?1";
                    cmd = new MySqlCommand( sqlstr );
                    cmd.Parameters.Add( "?1", MySqlDbType.String ).Value = account;
                }

                List<String> accountList = new List<String>();
                foreach ( DataRow item in wrapper.GetDataTable( cmd ).Rows )
                {
                    accountList.Add( Convert.ToString( item["login"] ) );
                }

                present( accountList, itemid, enchant, count );
            }
        }

        public static void present( int minlvl, int maxlvl, int itemid, int enchant, int count )
        {

            L1Item temp = ItemTable.getInstance().getTemplate( itemid );
            if ( temp == null )
            {
                return;
            }
            string sqlstr = "SELECT distinct(account_name) as account_name FROM characters WHERE level between ?1 and ?2";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = minlvl;
                cmd.Parameters.Add( "?2", MySqlDbType.Int32 ).Value = maxlvl;

                List<String> accountList = new List<String>();
                foreach ( DataRow item in wrapper.GetDataTable( cmd ).Rows )
                {
                    accountList.Add( Convert.ToString( item["account_name"] ) );
                }

                present( accountList, itemid, enchant, count );
            }

        }

        private static void present( List<String> accountList, int itemid, int enchant, int count )
        {

            L1Item temp = ItemTable.getInstance().getTemplate( itemid );
            if ( temp == null )
            {
                throw new Exception( "存在しないアイテムID" );
            }
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                string sqlstr;
                MySqlCommand cmd;
                foreach ( String account in accountList )
                {
                    if ( temp.isStackable() )
                    {
                        L1ItemInstance item = ItemTable.getInstance().createItem( itemid );
                        item.setEnchantLevel( enchant );
                        item.setCount( count );
                        sqlstr = @"INSERT INTO character_warehouse SET 
                                     id             = ?1,
                                     account_name   = ?2,
                                     item_id        = ?3,
                                     item_name      = ?4,
                                     count          = ?5,
                                     is_equipped    =0,
                                     enchantlvl     = ?6,
                                     is_id          = ?7,
                                     durability     = ?8,
                                     charge_count   = ?9,
                                     remaining_time = ?10";
                        cmd = new MySqlCommand( sqlstr );
                        cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = item.getId();
                        cmd.Parameters.Add( "?2", MySqlDbType.String ).Value = account;
                        cmd.Parameters.Add( "?3", MySqlDbType.Int32 ).Value = item.getItemId();
                        cmd.Parameters.Add( "?4", MySqlDbType.String ).Value = item.getName();
                        cmd.Parameters.Add( "?5", MySqlDbType.Int32 ).Value = item.getCount();
                        cmd.Parameters.Add( "?6", MySqlDbType.Int32 ).Value = item.getEnchantLevel();
                        cmd.Parameters.Add( "?7", MySqlDbType.Int32 ).Value = item.isIdentified() ? 1 : 0;
                        cmd.Parameters.Add( "?8", MySqlDbType.Int32 ).Value = item.get_durability();
                        cmd.Parameters.Add( "?9", MySqlDbType.Int32 ).Value = item.getChargeCount();
                        cmd.Parameters.Add( "?10", MySqlDbType.Int32 ).Value = item.getRemainingTime();
                        wrapper.ExecNonQuery( cmd );
                    }
                    else
                    {
                        L1ItemInstance item = null;
                        int createCount;
                        for ( createCount = 0; createCount < count; createCount++ )
                        {
                            item = ItemTable.getInstance().createItem( itemid );
                            item.setEnchantLevel( enchant );

                            sqlstr = @"INSERT INTO character_warehouse SET 
                                         id             = ?1,
                                         account_name   = ?2,
                                         item_id        = ?3,
                                         item_name      = ?4,
                                         count          = ?5,
                                         is_equipped    = 0,
                                         enchantlvl     = ?6,
                                         is_id          = ?7,
                                         durability     = ?8,
                                         charge_count   = ?9,
                                         remaining_time = ?10";
                            cmd = new MySqlCommand( sqlstr );
                            cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = item.getId();
                            cmd.Parameters.Add( "?2", MySqlDbType.String ).Value = account;
                            cmd.Parameters.Add( "?3", MySqlDbType.Int32 ).Value = item.getItemId();
                            cmd.Parameters.Add( "?4", MySqlDbType.String ).Value = item.getName();
                            cmd.Parameters.Add( "?5", MySqlDbType.Int32 ).Value = item.getCount();
                            cmd.Parameters.Add( "?6", MySqlDbType.Int32 ).Value = item.getEnchantLevel();
                            cmd.Parameters.Add( "?7", MySqlDbType.Int32 ).Value = item.isIdentified() ? 1 : 0;
                            cmd.Parameters.Add( "?8", MySqlDbType.Int32 ).Value = item.get_durability();
                            cmd.Parameters.Add( "?9", MySqlDbType.Int32 ).Value = item.getChargeCount();
                            cmd.Parameters.Add( "?10", MySqlDbType.Int32 ).Value = item.getRemainingTime();
                            wrapper.ExecNonQuery( cmd );
                        }
                    }
                }
            }
        }
        private static Logger _log = Logger.getLogger( typeof( L1DwarfInventory ).FullName );
        private L1PcInstance _owner;
    }
}
